package cn.gov.msa.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import net.sf.json.JSONObject;

@RestController
@RequestMapping(value="/user")
public class UserLoginController {

	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestBody JSONObject param,HttpSession session)throws Exception{
		session.setAttribute("user", param);
		return "{\"result\":\"1\",\"info\":\"登陆成功\",\"datas\":"+param+"}";
	}
	
	@RequestMapping(value="/validate",method=RequestMethod.POST)
	public String validate(HttpSession session)throws Exception{
		JSONObject userName = JSONObject.fromObject(session.getAttribute("user"));
	    if(!userName.isEmpty()) {
	    	return "{\"result\":\"1\",\"info\":\"成功\",\"datas\":"+userName+"}";
	    }else {
	    	return "{\"result\":\"0\",\"info\":\"失败\"}";
	    }
	}
	
	@RequestMapping(value="/logout",method=RequestMethod.POST)
	public String logout(HttpSession session) throws Exception{
		session.invalidate();
		return "{\"result\":\"1\",\"info\":\"注销成功\"}";
	}
	
	@RequestMapping(value = "/getUser", method = RequestMethod.POST)
	public String getUser( HttpSession session, HttpServletRequest httpRequest) throws Exception {
		String result = "{\"result\":0,\"info\":\"还未登录！\"}";
		JSONObject userinfo = new JSONObject();
		try{
			userinfo = JSONObject.fromObject(session.getAttribute("user"));
		}
		catch(Exception e){
			result = "{\"result\":0,\"info\":\"还未登录！\"}";
		}
		if(!userinfo.isNullObject() && !userinfo.isEmpty()){
			JSONObject jsonUser = new JSONObject();
			jsonUser.put("userid", userinfo.getString("userId"));
			jsonUser.put("company", userinfo.getString("company"));
			jsonUser.put("companyid", userinfo.getString("companyId"));
			jsonUser.put("contactaddr", userinfo.getString("contactAddr"));
			jsonUser.put("email", userinfo.getString("email"));
			jsonUser.put("mobilephone", userinfo.getString("mobilePhone"));
			jsonUser.put("proposer", userinfo.getString("proposer"));
			jsonUser.put("proposerid", userinfo.getString("proposerId"));
			jsonUser.put("telephone", userinfo.getString("telePhone"));
			jsonUser.put("result", 1);	
			result = jsonUser.toString();
		}			    	
        return result;  
    } 
}
